var express = require('express');
var userModel = require('../../modules/userModel')
var md5 = require('md5')
const jwt = require('jsonwebtoken')
const {
	KEY
} = require('../../config/token')
var router = express.Router();

/* GET home page. */


router.get('/login', function (req, res, next) {
	res.render('auth/login', {
		title: '登录'
	});

});
router.post('/login', function (req, res, next) {
	userModel.findOne({
		username: req.body.username,
		password: md5(req.body.password)
	}).then(data => {
		console.log(data)

		if (data) {
			let token = jwt.sign({
				username: data.username,
				_id: data._id
			}, KEY, {
				expiresIn: 60 * 60 * 7
			})
			res.json({
				code: '0000',
				msg: '登录成功',
				data: token
			})
		} else {
			return res.json({
				code: '2001',
				msg: '登录失败,账号或密码错误',
				data: null
			})
		}
	}).catch(err => {
		res.json({
			code: '2002',
			msg: '登录失败,服务器错误',
			data: null
		})
		console.log(err)
	})
});
router.get('/logout', function (req, res, next) {
	req.session.destroy(() => { //销毁session
		res.redirect('/auth/login')
	})
});

module.exports = router;